package com.focusai.efairy.ui.activity.project;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;

import com.focusai.efairy.R;
import com.focusai.efairy.model.request.GetDevMoreRequest;
import com.focusai.efairy.model.response.ProjectManageResponse;
import com.focusai.efairy.network.HttpManager;
import com.focusai.efairy.network.Response;
import com.focusai.efairy.network.exception.NetworkException;
import com.focusai.efairy.ui.adapter.project.ProjectSelectDevAdapter;
import com.focusai.efairy.ui.base.SwipeBackTipBaseActivity;
import com.mylhyl.crlayout.SwipeRefreshAdapterView;
import com.mylhyl.crlayout.SwipeRefreshRecyclerView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by luo_guangwen on 2017/9/12.
 */

public class ProjectSelectDevListActivity extends SwipeBackTipBaseActivity implements SwipeRefreshLayout.OnRefreshListener,
        SwipeRefreshAdapterView.OnListLoadListener {
    public static final String KEY_PROJECT_ID = "key_project_id";
    public static final String KEY_SELETED_ITEMS = "key_seleted_items";
    private SwipeRefreshRecyclerView mRefreshRecyclerView;
    private ProjectSelectDevAdapter mAdapter;
    private List<ProjectManageResponse.DevItem> mList;
    private String projectId;
    private  List<ProjectManageResponse.DevItem> hasSelectList;
    private int efairyproject_total_devices;//总用户数
    private boolean isAllselect = false;
    private MenuItem menuItem2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_list);
        initView();
        setDefaultValues();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menuItem2 = menu.add(MENU_GROUP_ID, MENU_ITEM_ADD, 0, "全选").setTitle("全选");
        MenuItem menuItem1 = menu.add(MENU_GROUP_ID, MENU_ITEM_SAVE, 0, R.string.sure).setTitle(R.string.sure);
        MenuItemCompat.setShowAsAction(menuItem1, MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
        MenuItemCompat.setShowAsAction(menuItem2, MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == MENU_ITEM_SAVE) {
            if (mList != null && mList.size() > 0){
                ArrayList<ProjectManageResponse.DevItem> ids = new ArrayList<>();
                for (ProjectManageResponse.DevItem devItem: mList){
                    if (devItem.isSelected){
                        ids.add(devItem);
                    }
                }
                if (ids.size() == 0){
                    showToast("未选择设备");
                    return super.onOptionsItemSelected(item);
                }
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putSerializable(KEY_SELETED_ITEMS,ids);
                intent.putExtras(bundle);
                setResult(RESULT_OK,intent);
                finish();
            }
        }else if(item.getItemId() == MENU_ITEM_ADD){
             if(!isAllselect){//如果没有全选择，执行全选功能
                 for(ProjectManageResponse.DevItem devItem : mList){
                     devItem.isSelected = true;
                 }
                  mAdapter.notifyDataSetChanged();
                 isAllselect = true;
                 item.setTitle("全不选");
             }else{//如果全选择，则执行取消所有的选择
                 for(ProjectManageResponse.DevItem devItem : mList){
                     devItem.isSelected = false;
                 }
                 mAdapter.notifyDataSetChanged();
                 isAllselect = false;
                 item.setTitle("全选");
             }

        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void initView() {
        mRefreshRecyclerView = findView(R.id.swipe_recyce_view);
    }

    @Override
    protected void setDefaultValues() {
        setCenterTitleName("给用户分配设备");
        mAdapter = new ProjectSelectDevAdapter();
        mList = new ArrayList<>();
        mRefreshRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRefreshRecyclerView.setAdapter(mAdapter);
        mAdapter.refreshData(mList);
        mRefreshRecyclerView.setOnListLoadListener(this);
        mRefreshRecyclerView.setOnRefreshListener(this);
        if (getIntent() != null && getIntent().getExtras() != null){
            projectId = getIntent().getExtras().getString(KEY_PROJECT_ID);
            hasSelectList = (List<ProjectManageResponse.DevItem>) getIntent().getExtras().getSerializable(KEY_SELETED_ITEMS);
        }
        if (TextUtils.isEmpty(projectId)){
            showToast("项目id为空");
            finish();
        }
        mRefreshRecyclerView.setRefreshing(true);
        mRefreshRecyclerView.setLoading(false);
        mRefreshRecyclerView.setEnabledLoad(false);
    }

    @Override
    public void onRefresh() {
        if(efairyproject_total_devices == mList.size() && mList.size() != 0){
            showToast("没有数据了");
            mRefreshRecyclerView.setRefreshing(false);
        }else{
            refresh();
        }

    }

    @Override
    public void onListLoad() {
//        loadMore();
    }

    private void refresh(){
        HttpManager.getInstance().sendRequest(new GetDevMoreRequest(projectId, 0, "",
                new Response.Listener<ProjectManageResponse.DevItems>() {
                    @Override
                    protected void onSuccess(ProjectManageResponse.DevItems response) {
                        if (response != null && response.device_list != null){
                            mList.clear();
                            mList.addAll(response.device_list);
                            int i = 0;
                            if (hasSelectList != null){
                                for (ProjectManageResponse.DevItem item : hasSelectList){
                                    for (ProjectManageResponse.DevItem devItem : response.device_list){
                                        if (item.efairydevice_id == devItem.efairydevice_id){
                                            i++;
                                            devItem.isSelected = true;
                                            break;
                                        }
                                    }
                                }
                            }
                            mAdapter.notifyDataSetChanged();
//                            if (GetUserListRequest.size > mList.size()){
//                                mRefreshRecyclerView.setEnabledLoad(false);
//                            }else {
//                                mRefreshRecyclerView.setEnabledLoad(true);
//                            }
                            efairyproject_total_devices  = response.efairyproject_total_devices;
                            if(i == efairyproject_total_devices && i > 0){
                                isAllselect = true;
                                menuItem2.setTitle("全不选");
                            }
                            mRefreshRecyclerView.setRefreshing(false);
                        }
                        showTip(mList);
                    }

                    @Override
                    protected void onFail(NetworkException exception) {
                        doException(exception);
                        mRefreshRecyclerView.setRefreshing(false);
                        showTip(mList);
                    }
                }));
    }
    private void loadMore(){
        if (mList.size() == 0){
            mRefreshRecyclerView.setLoading(false);
            return;
        }
        HttpManager.getInstance().sendRequest(new GetDevMoreRequest(projectId, mList.get(mList.size() - 1).efairydevice_id, "",
                new Response.Listener<ProjectManageResponse.DevItems>() {
                    @Override
                    protected void onSuccess(ProjectManageResponse.DevItems response) {
                        if (response != null && response.device_list != null){

                            mList.addAll(response.device_list);
                            if (hasSelectList != null){
                                for (ProjectManageResponse.DevItem item : hasSelectList){
                                    for (ProjectManageResponse.DevItem devItem : response.device_list){
                                        if (item.efairydevice_id == devItem.efairydevice_id){
                                            devItem.isSelected = true;
                                            break;
                                        }
                                    }
                                }
                            }
                            mAdapter.notifyDataSetChanged();
                            if (mList.size() == response.efairyproject_total_devices){
                                mRefreshRecyclerView.setEnabledLoad(false);
                            }else {
                                mRefreshRecyclerView.setEnabledLoad(true);
                            }
                            mRefreshRecyclerView.setLoading(false);
                        }
                    }

                    @Override
                    protected void onFail(NetworkException exception) {
                        doException(exception);
                        mRefreshRecyclerView.setLoading(false);
                    }
                }));
    }
}
